Summernote image upload with carrierwave

jamesperet 9 years ago
parent
commit
984428128c
3 changed files with 32 additions and 1 deletions
  1. 23 1
      app/assets/javascripts/blog_posts.js.coffee
  2. 8 0
      app/controllers/blog_posts_controller.rb
  3. 1 0
      config/routes.rb

+ 23 - 1
app/assets/javascripts/blog_posts.js.coffee

@@ -1,3 +1,5 @@
1
+
2
+
1 3
 attachRatingHandler = ->
2 4
 
3 5
   # to set summernote object
@@ -8,6 +10,9 @@ attachRatingHandler = ->
8 10
   summer_note.summernote
9 11
     # to set options
10 12
     height:300
13
+    onImageUpload: (files, editor, welEditable) ->
14
+      sendFile files[0], editor, welEditable
15
+        
11 16
     # toolbar: [
12 17
                 # ['insert', ['picture', 'link']], // no insert buttons
13 18
                 # ["table", ["table"]],
@@ -28,6 +33,23 @@ attachRatingHandler = ->
28 33
     # alert $('#post_content').code()
29 34
     summer_note.val summer_note.code()
30 35
     true
36
+
37
+sendFile = (file, editor, welEditable) ->
38
+	data = new FormData()
39
+	data.append("file", file)
40
+	$.ajax {
41
+		url: '/upload',
42
+		data: data,
43
+		cache: false,
44
+		contentType: false,
45
+		processData: false,
46
+		type: 'POST',
47
+		success: (data) ->
48
+			editor.insertImage(welEditable, data.url)
49
+		error: (data) ->
50
+			editor.insertImage(welEditable, data.url)
51
+			alert(data.url)
52
+	}    
31 53
     
32 54
 $(document).ready attachRatingHandler
33
-$(document).on "page:load", attachRatingHandler
55
+$(document).on "page:load", attachRatingHandler

+ 8 - 0
app/controllers/blog_posts_controller.rb

@@ -63,6 +63,14 @@ class BlogPostsController < ApplicationController
63 63
       format.json { head :no_content }
64 64
     end
65 65
   end
66
+  
67
+  def upload
68
+      @file = params[:file]
69
+      @upload = Upload.create(:file => @file)
70
+      @upload.save
71
+
72
+      render(json: {:url => @upload.file.to_s })
73
+  end
66 74
 
67 75
   private
68 76
     # Use callbacks to share common setup or constraints between actions.

+ 1 - 0
config/routes.rb

@@ -7,6 +7,7 @@ RailsWebsiteTemplate::Application.routes.draw do
7 7
   get "admin/posts" => "admin_panel#posts", :as => :admin_posts
8 8
   get "admin/users" => "admin_panel#users", :as => :admin_users
9 9
   
10
+  post "upload" => "blog_posts#upload", :as => :post_upload
10 11
   get "blog" => "blog_posts#index", :as => :blog
11 12
   get "post/:id" => "blog_posts#show", :as => :post
12 13
   resources :blog_posts, path: '/admin/posts'